package com.sky.controller.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController("userDishController")
@RequestMapping("/user/dish")
@Slf4j
@Api(tags = "C端-菜品浏览接口")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result<List<DishVO>> list(Long categoryId) {

        // 使用 redis 缓存菜品数据，提高查询速度

        // 构造 key：dish_categoryId
        String key = "dish" + categoryId;

        // 查询是否存在

        // 取数据格式为字符串
        String dishVOListString = (String) redisTemplate.opsForValue().get(key);

        if (dishVOListString != null && !dishVOListString.isEmpty()) {
            // 存在则直接返回

            // 返回
            return Result.success(JSONObject.parseObject(dishVOListString, List.class));
        }

        // 不存在,则查询MySQL后，存入Redis，再返回

        // 查询数据库
        List<DishVO> dishVOList = dishService.listByCategoryIdWithFlavor(categoryId);

        // 查询结果存入 Redis

        // 插入数据格式设置为 JSON 字符串
        redisTemplate.opsForValue().set(key, JSON.toJSONString(dishVOList));

        return Result.success(dishVOList);

    }

}
